<template>
  <div>
    <!-- 搜索框 -->
    <!-- Tips: 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮。 -->
    <form action="/">
      <van-search
        v-model.trim="keywords"
        background="#3296fa"
        placeholder="请输入搜索关键词"
        show-action
        class="search"
        @search="onSearch"
        @focus="onFocus"
        @cancel="$router.back()"
      />
    </form>
    <!-- 搜索历史/建议/结果 -->
    <!-- <search-history></search-history>
    <search-result></search-result>
    <search-suggestion></search-suggestion> -->
    <component
      :is="componentName"
      :keywords="keywords"
      @search="onSearch"
    ></component>
  </div>
</template>

<script>
import SearchSuggestion from './components/SearchSuggestion.vue'
import SearchResult from './components/SearchResult'
import SearchHistory from './components/SearchHistory.vue'

export default {
  name: 'search',
  components: {
    SearchSuggestion,
    SearchResult,
    SearchHistory
  },
  data() {
    return {
      keywords: '',
      isShowResult: false,
      keyList: []
    }
  },
  computed: {
    // 动态计算组件的显示条件
    componentName() {
      // 当关键词为空时 显示历史
      if (!this.keywords) {
        return 'SearchHistory'
      }
      // 按下确认 触发search事件时 显示结果
      if (this.isShowResult) {
        return 'SearchResult'
      }
      // 既不为空 也不确认时  显示建议
      return 'SearchSuggestion'
    }
  },
  methods: {
    // 用户确认搜索时触发
    onSearch(val) {
      // this.$toast(val)
      this.isShowResult = true
      // 处理keyword 存到仓库
      this.$store.commit('SET_KEYLIST', val)
    },
    // 用户重新聚焦输入框时触发  让componentName重新计算显示
    onFocus() {
      this.isShowResult = false
    }
  }
}
</script>

<style scoped lang="less">
.search {
  [role='button'] {
    color: #fff;
  }
}
</style>
